<template>
  <div class="elUpload">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :http-request="upload"
      :on-change="handleChange"
      :file-list="fileList"
      :class="{ disabled: isDisabled }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="showDialog" title="hhh">
      <img width="100%" :src="ImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
// 导入
import COS from 'cos-js-sdk-v5'
// 实例化一个操作腾讯云的对象
let cos = new COS({
  // 密钥id
  SecretId: 'AKID3uVquhDTSt3xaw1pNeeNp0vZx4uTlnY2',
  // 密钥key
  SecretKey: 'ECtJSLxHK6crqYz92e06vTkkTv5zcaHh'
})

export default {
  data () {
    return {
      ImageUrl: '',
      showDialog: false,
      fileList: []
    }
  },
  methods: {
    // 删除事件
    handleRemove (file, fileList) {
      this.fileList = []
    },
    //放大镜
    handlePictureCardPreview (file) {
      this.ImageUrl = file.url
      this.showDialog = true
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange (file, fileList) {
      this.fileList = fileList
    },
    upload (params) {
      cos.putObject(
        {
          Bucket: 'hr72-1306809256' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: params.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: params.file // 上传文件对象
          //   onProgress: function (progressData) {
          //     console.log(JSON.stringify(progressData))
          //   }
        },
        (err, data) => {
          if (!err) {
            this.fileList = [{ url: 'http://' + data.Location }]
          }
        }
      )
    }
  },
  computed: {
    isDisabled () {
      return this.fileList.length > 0
    }
  }
}
</script>

<style lang="scss">
.elUpload {
  .disabled {
    .el-upload.el-upload--picture-card {
      display: none;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
